package cn.stylefeng.guns.modular.basic.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.stylefeng.guns.modular.basic.model.result.BasicCarrierResult;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCarrier;
import cn.stylefeng.guns.modular.basic.entity.BasicDriver;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.model.params.BasicCarrierParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicDriverParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicOilCardParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPrivatecarParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicDriverResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPrivatecarResult;
import cn.stylefeng.guns.modular.basic.service.BasicCarrierService;
import cn.stylefeng.guns.modular.basic.service.BasicDriverService;
import cn.stylefeng.guns.modular.basic.service.BasicOilCardService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPrivatecarService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 自有车档案表控制器
 */
@Controller
@RequestMapping("/basicPrivatecar")
public class BasicPrivatecarController extends BaseController {

    private String PREFIX = "/basic/basicPrivatecar";

    @Autowired
    private BasicPrivatecarService basicPrivatecarService;

    @Autowired
    private UserService userService;

	@Autowired
	private RoleService roleService;

    @Autowired
    private BasicCarrierService basicCarrierService;

    @Autowired
    private BasicOilCardService basicOilCardService;

    @Autowired
    private BasicOperateService basicOperateService;
    
    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/basicPrivatecar.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择油卡
    	BasicOilCardParam basicOilCardParam = new BasicOilCardParam();
    	basicOilCardParam.setDeliverId(deliverId);
    	model.addAttribute("basicOilCardlist", basicOilCardService.findListBySpec(basicOilCardParam,null));
        return PREFIX + "/basicPrivatecar_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Model model,Integer id) {
    	User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
		BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(id);
		//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择承运商
    	BasicCarrierParam basicCarrierParam = new BasicCarrierParam();
    	basicCarrierParam.setDeliverId(deliverId);
		basicCarrierParam.setOperateId(basicPrivatecar.getOperateId());
    	model.addAttribute("carrierlist", basicCarrierService.findListBySpec(basicCarrierParam,basicPrivatecar.getOperateId()));
    	//查询可选择油卡
    	BasicOilCardParam basicOilCardParam = new BasicOilCardParam();
    	basicOilCardParam.setDeliverId(deliverId);
    	model.addAttribute("basicOilCardlist", basicOilCardService.findListBySpec(basicOilCardParam,null));
        return PREFIX + "/basicPrivatecar_edit.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/privatecar.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("车辆模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  BasicPrivatecarParam basicPrivatecarParam)  {
		ResponseData data = new ResponseData();
		try {
			data = basicPrivatecarService.getExceldata(file,basicPrivatecarParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 选择司机页面
     */
    @RequestMapping("/toDriver")
    public String toDriver(Model model) {
    	User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/chooseDriver.html";
    }

    @Autowired
    private BasicDriverService basicDriverService;

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BasicPrivatecarParam basicPrivatecarParam) {
    	User user = userService.getcurrentUser();
    	
    	if(ToolUtil.isEmpty(basicPrivatecarParam.getPrivatecarSurevolume())) {
    		return ResponseData.error("Please fill in the approved loading volume");
    	} else {
    		BigDecimal privatecarSurevolumebig = new BigDecimal(basicPrivatecarParam.getPrivatecarSurevolume()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    		basicPrivatecarParam.setPrivatecarSurevolume(privatecarSurevolumebig.toString());
    	}
        
        BasicPrivatecarParam basicPrivatecarParam1 = new BasicPrivatecarParam();
        basicPrivatecarParam1.setPrivatecarCarnumber(basicPrivatecarParam.getPrivatecarCarnumber());
        basicPrivatecarParam1.setDeliverId(user.getDeliverId());
        List<BasicPrivatecarResult> list = basicPrivatecarService.findBySpecList(basicPrivatecarParam1,null);
        if (list.size() >0){
            return ResponseData.error("License Plate Number Already Exists");
        }

    	Object operateId = basicPrivatecarParam.getOperateId();
    	if (operateId!=null) {
    		BasicOperate basicOperate = basicOperateService.getById(Integer.parseInt(operateId.toString()));
    		basicPrivatecarParam.setOperateName(basicOperate.getOperateName());
		}

    	Object privatecarFleetId = basicPrivatecarParam.getPrivatecarFleetId();
    	BasicCarrier basicCarrier = new BasicCarrier();
    	if (privatecarFleetId != null) {
    		basicCarrier = basicCarrierService.getById(Integer.parseInt(privatecarFleetId.toString()));
    		basicPrivatecarParam.setPrivatecarFleetName(basicCarrier.getCarrierName());
		}
    	
    	if(ToolUtil.isNotEmpty(basicPrivatecarParam.getSettlement())) {
    		if(basicPrivatecarParam.getSettlement().equals("Carrier")) {
    	    	if (privatecarFleetId!=null) {
    	    		basicPrivatecarParam.setPayee(basicCarrier.getPayee());
    	    		basicPrivatecarParam.setBank(basicCarrier.getBank());
    	    		basicPrivatecarParam.setBankAddress(basicCarrier.getBankAddress());
    	    		basicPrivatecarParam.setBankAccount(basicCarrier.getBankAccount());
    	    		basicPrivatecarParam.setBankNo(basicCarrier.getBankNo());
    	    		basicPrivatecarParam.setCycle(basicCarrier.getCycle());
    	    		basicPrivatecarParam.setTaxRate(basicCarrier.getTaxRate());
    	    		basicPrivatecarParam.setOilCardNumber(basicCarrier.getOilCardNumber());
    			} else {
    	            return ResponseData.error("Please select a carrier");
    			}
    		}
    		if(basicPrivatecarParam.getSettlement().equals("Driver")) {
    			BasicDriverParam basicDriverParam = new BasicDriverParam();
    			basicDriverParam.setDriverName(basicPrivatecarParam.getDriver1());
    			basicDriverParam.setTel(basicPrivatecarParam.getTel1());
    			basicDriverParam.setDeptId(user.getDeptId());
    			BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,user.getOperateId());
    			if(basicDriverResult != null) {
    	    		basicPrivatecarParam.setPayee(basicDriverResult.getPayee());
    	    		basicPrivatecarParam.setBank(basicDriverResult.getBank());
    	    		basicPrivatecarParam.setBankAddress(basicDriverResult.getBankAddress());
    	    		basicPrivatecarParam.setBankAccount(basicDriverResult.getBankAccount());
    	    		basicPrivatecarParam.setBankNo(basicDriverResult.getBankNo());
    	    		basicPrivatecarParam.setCycle(basicDriverResult.getCycle());
    	    		basicPrivatecarParam.setTaxRate(basicDriverResult.getTaxRate());
    	    		basicPrivatecarParam.setOilCardNumber(basicDriverResult.getOilCardNumber());
    			}
    		}
    	}
    	
    	//解除司机绑定的其他车辆
    	basicPrivatecarService.lambdaUpdate()
    	.eq(BasicPrivatecar::getDriverId1, basicPrivatecarParam.getDriverId1())
    	.eq(BasicPrivatecar::getPrivatecarState, "IDLE")
    	.set(BasicPrivatecar::getDriverId1, null)
    	.set(BasicPrivatecar::getDriver1, null)
    	.set(BasicPrivatecar::getTel1, null)
    	.update();
        
        basicPrivatecarParam.setDeliverId(user.getDeliverId());
        basicPrivatecarParam.setDeptId(user.getDeptId());
        basicPrivatecarParam.setPrivatecarState("IDLE");
        this.basicPrivatecarService.add(basicPrivatecarParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BasicPrivatecarParam basicPrivatecarParam) {
    	User user = userService.getcurrentUser();
    	
    	if(ToolUtil.isEmpty(basicPrivatecarParam.getPrivatecarSurevolume())) {
    		return ResponseData.error("Please fill in the approved loading volume");
    	} else {
    		BigDecimal privatecarSurevolumebig = new BigDecimal(basicPrivatecarParam.getPrivatecarSurevolume()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    		basicPrivatecarParam.setPrivatecarSurevolume(privatecarSurevolumebig.toString());
    	}
        
        BasicPrivatecarParam basicPrivatecarParam1 = new BasicPrivatecarParam();
        basicPrivatecarParam1.setId(basicPrivatecarParam.getId());
        basicPrivatecarParam1.setPrivatecarCarnumber(basicPrivatecarParam.getPrivatecarCarnumber());
        basicPrivatecarParam1.setDeliverId(user.getDeliverId());
        List<BasicPrivatecarResult> list = basicPrivatecarService.findBySpecList(basicPrivatecarParam1,null);
        if (list.size() > 0){
            return ResponseData.error("License Plate Number Already Exists");
        }

    	Object operateId = basicPrivatecarParam.getOperateId();
    	if (operateId!=null) {
    		BasicOperate basicOperate = basicOperateService.getById(Integer.parseInt(operateId.toString()));
    		basicPrivatecarParam.setOperateName(basicOperate.getOperateName());
		}

    	Object privatecarFleetId = basicPrivatecarParam.getPrivatecarFleetId();
    	BasicCarrier basicCarrier = new BasicCarrier();
    	if (privatecarFleetId != null) {
    		basicCarrier = basicCarrierService.getById(Integer.parseInt(privatecarFleetId.toString()));
    		basicPrivatecarParam.setPrivatecarFleetName(basicCarrier.getCarrierName());
		}
    	
    	if(ToolUtil.isNotEmpty(basicPrivatecarParam.getSettlement())) {
    		if(basicPrivatecarParam.getSettlement().equals("Carrier")) {
    	    	if (privatecarFleetId!=null) {
    	    		basicPrivatecarParam.setPayee(basicCarrier.getPayee());
    	    		basicPrivatecarParam.setBank(basicCarrier.getBank());
    	    		basicPrivatecarParam.setBankAddress(basicCarrier.getBankAddress());
    	    		basicPrivatecarParam.setBankAccount(basicCarrier.getBankAccount());
    	    		basicPrivatecarParam.setBankNo(basicCarrier.getBankNo());
    	    		basicPrivatecarParam.setCycle(basicCarrier.getCycle());
    	    		basicPrivatecarParam.setTaxRate(basicCarrier.getTaxRate());
    	    		basicPrivatecarParam.setOilCardNumber(basicCarrier.getOilCardNumber());
    			} else {
    	            return ResponseData.error("Please select a carrier");
    			}
    		}
    		if(basicPrivatecarParam.getSettlement().equals("Driver")) {
    			BasicDriverParam basicDriverParam = new BasicDriverParam();
    			basicDriverParam.setDeptId(user.getDeptId());
    			basicDriverParam.setDriverName(basicPrivatecarParam.getDriver1());
    			basicDriverParam.setTel(basicPrivatecarParam.getTel1());
    			BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,user.getOperateId());
    			if(basicDriverResult != null) {
    	    		basicPrivatecarParam.setPayee(basicDriverResult.getPayee());
    	    		basicPrivatecarParam.setBank(basicDriverResult.getBank());
    	    		basicPrivatecarParam.setBankAddress(basicDriverResult.getBankAddress());
    	    		basicPrivatecarParam.setBankAccount(basicDriverResult.getBankAccount());
    	    		basicPrivatecarParam.setBankNo(basicDriverResult.getBankNo());
    	    		basicPrivatecarParam.setCycle(basicDriverResult.getCycle());
    	    		basicPrivatecarParam.setTaxRate(basicDriverResult.getTaxRate());
    	    		basicPrivatecarParam.setOilCardNumber(basicDriverResult.getOilCardNumber());
    			}
    		}
    	}
    	
    	//解除司机绑定的其他车辆
    	basicPrivatecarService.lambdaUpdate()
    	.ne(BasicPrivatecar::getId, basicPrivatecarParam.getId())
    	.eq(BasicPrivatecar::getDriverId1, basicPrivatecarParam.getDriverId1())
    	.eq(BasicPrivatecar::getPrivatecarState, "IDLE")
    	.set(BasicPrivatecar::getDriverId1, null)
    	.set(BasicPrivatecar::getDriver1, null)
    	.set(BasicPrivatecar::getTel1, null)
    	.update();
    	
        this.basicPrivatecarService.update(basicPrivatecarParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BasicPrivatecarParam basicPrivatecarParam) {
        this.basicPrivatecarService.delete(basicPrivatecarParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BasicPrivatecarParam basicPrivatecarParam) {
        BasicPrivatecar detail = this.basicPrivatecarService.getById(basicPrivatecarParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BasicPrivatecarParam basicPrivatecarParam,String condition ,String channeltype) {
    	User user = userService.getcurrentUser();
        basicPrivatecarParam.setDeliverId(user.getDeliverId());
		String roleId = user.getRoleId();
		if(ToolUtil.isNotEmpty(roleId)){
			for(String rId : roleId.split(",")){
				Role byId = roleService.getById(rId);
				if(byId != null && byId.getName().contains("Carrier")){
					BasicCarrierParam param = new BasicCarrierParam();
					param.setUserId(user.getUserId());
					BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
					if(bySpec != null){
						basicPrivatecarParam.setPrivatecarFleetId(bySpec.getId());
					}else{
						basicPrivatecarParam.setPrivatecarFleetId(-1);
					}
				}
			}
		}
        return this.basicPrivatecarService.findPageBySpec(basicPrivatecarParam,condition,user.getDeptId(),channeltype,user.getOperateId());
    }

}


